package org.tlipoca.smarticle.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.genntii.smcommon.constant.GatewayConstant;
import org.genntii.smcommon.result.PageResult;
import org.genntii.smcommon.result.Result;
import org.genntii.smdomain.doc.ArticleDoc;
import org.genntii.smdomain.dto.ArticleItemDTO;
import org.genntii.smdomain.dto.ChannelArticleDTO;
import org.genntii.smdomain.vo.ArticleDetailVO;
import org.genntii.smdomain.vo.ArticleVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.tlipoca.smarticle.service.ArticleService;
import org.tlipoca.smarticle.service.EsArticleService;
import org.tlipoca.smarticle.utils.IpUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Map;

@Tag(name = "/article")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private ArticleService articleService;

    @Resource
    private EsArticleService esArticleService;

    @GetMapping("/userTotal/{userId}")
    public Result<Long> getTotal(@PathVariable Long userId){
        return Result.success(articleService.getTotalUserArticleByUserId(userId));
    }

    @GetMapping("/articleLimit")
    public Result<ArrayList<ArticleVO>> getArticleLimit(@RequestParam("userId") Long userId,
                                                        @RequestParam("pageNum") Integer pageNum,
                                                        @RequestParam("pageSize") Integer pageSize){
        return Result.success(articleService.getArticleLimit(userId, pageNum, pageSize));
    }

    @Operation(summary = "根据频道获取文章")
    @GetMapping("getByChannel")
    public Result<ArrayList<ArticleVO>> getArticleByDate(@RequestParam("channelId")Long channelId){
        return null;
    }


    @GetMapping("/latest")
    @Operation(summary = "按照时间搜索")
    public Result<PageResult<ArticleVO>> getArticleLatest(@RequestParam("pageNum") Integer pageNum,
                                                          @RequestParam("pageSize") Integer pageSize,
                                                          @RequestParam("order") Integer articleOrder,
                                                          @RequestParam("subscribeFilter") Integer articleSubscribeFilter,
                                                          HttpServletRequest request){
        Long userId = Long.valueOf(request.getHeader(GatewayConstant.USER_ID));
        return Result.success(articleService.getLatestArticle(pageNum,pageSize, articleOrder, articleSubscribeFilter, userId));
    }

    @GetMapping("setLike")
    public Result setLike(@RequestParam("like") Integer like,
                          @RequestParam("dislike") Integer dislike,
                          @RequestParam("articleId") Long articleId){
        articleService.setLike(like,dislike,articleId);
        return Result.success();
    }

    @GetMapping("/exists")
    @Operation(summary = "文章是否存在")
    public Result<Boolean> articleExists(@RequestParam("articleId") Long articleId) {
        return Result.success(articleService.articleExistsService(articleId));
    }

    @PostMapping
    @Operation(summary = "新增文章")
    public Result addArticle(@RequestBody ArticleItemDTO articleItemDTO, HttpServletRequest request) {
        String ipv4 = IpUtil.getIpAddr(request);
        Long userId = Long.valueOf(request.getHeader(GatewayConstant.USER_ID));
        articleService.addArticleService(articleItemDTO,ipv4,userId);
        return Result.success();
    }

    @Operation(summary = "删除文章")
    @DeleteMapping("/{articleId}")
    public Result deleteArticle(@PathVariable Long articleId) {
        articleService.deleteArticleService(articleId);
        return Result.success();
    }

    @Operation(summary = "更新文章状态")
    @PutMapping("/status/{articleId}")
    public Result updateArticleStatus(@PathVariable Long articleId, @Param("status") Integer status) {
        articleService.updateArticleStatusService(articleId, status);
        return Result.success();
    }

    @Operation(summary = "修改文章")
    @PutMapping("/{articleId}")
    public Result updateArticle(@PathVariable Long articleId, @RequestBody ArticleItemDTO articleItemDTO) {
        articleService.updateArticleService(articleId, articleItemDTO);
        return Result.success();
    }

    @Operation(summary = "根据ID查询文章")
    @GetMapping("/{articleId}")
    public Result<ArticleDetailVO> getArticleById(@PathVariable Long articleId,HttpServletRequest request) {
        Long userId = Long.valueOf(request.getHeader(GatewayConstant.USER_ID));
        return Result.success(articleService.getArticleByIdService(articleId,userId));
    }

    @Operation(summary = "根据ID查询文章列表")
    @GetMapping
    public Result<ArrayList<ArticleDetailVO>> getArticleListByIds(@RequestParam("ids") ArrayList<Long> ids, HttpServletRequest request) {
        Long userId = Long.valueOf(request.getHeader(GatewayConstant.USER_ID));
        return Result.success(articleService.getArticleListByIdsService(ids,userId));
    }

    @Operation(summary = "根据Id查询文章列表")
    @GetMapping("batch")
    public Result<ArrayList<ArticleVO>> getArticleVOByIds(@RequestParam("ids")ArrayList<Long> ids,
                                                          @RequestParam("userId")Long userId){
        return Result.success(articleService.getArticleVObyIds(ids,userId));
    }

    @Operation(summary = "根据频道ID查询文章列表")
    @GetMapping("/channel/{channelId}")
    public Result getArticleListByChannelId() {
        // TODO. ElasticSearch 根据频道ID查询文章列表
        return Result.success();
    }

    @Operation(summary = "根据标签ID查询文章列表")
    @GetMapping("/article_tag/{tagId}")
    public Result getArticleListByArticleTagId() {
        // TODO. ElasticSearch 根据标签ID 查询文章列表
        return Result.success();
    }

    @Operation(summary = "查询文章列表")
    @GetMapping("/search")
    public Result<PageResult<ArticleDoc>> searchArticle(@RequestParam("keyword") String  keyword,
                                                       @RequestParam("pageNum") Integer pageNum,
                                                       @RequestParam("pageSize") Integer pageSize) {
        return Result.success(esArticleService.search(keyword,pageNum,pageSize));
    }

    @Operation(summary = "根据Ids返回文章列表")
    @GetMapping("list")
    public Result<ArrayList<ArticleVO>> articleList(@RequestParam("articleIds") ArrayList<Long> articleIds){

        return Result.success(articleService.articleList(articleIds));

    }
    @Operation(summary = "文章点踩")
    @PostMapping("/like/{articleId}")
    public Result articleLike(@RequestParam("like") int like, @RequestParam("dislike") int dislike, @PathVariable Long articleId){
        articleService.articleLikeUpdate(like,dislike,articleId);
        return Result.success();
    }

    @Operation(summary = "批量上传图片")
    @PostMapping("/picBatchUpload")
    public Result<Map<Integer, String>> picBatchUpload(@RequestPart("files") MultipartFile[] files){
        return Result.success(articleService.BatchUpload(files));
    }

    @Operation(summary = "根据用户id查找文章")
    @GetMapping("/getByUser/{userId}")
    public Result<ArrayList<ArticleVO>> getArticleByUserId(@PathVariable Long userId){
        return Result.success(articleService.getArticleByUserId(userId));
    }

    @Operation(summary = "根据频道id获取文章")
    @PostMapping("/channelArticle")
    public Result<ArrayList<ArticleVO>> channelArticle(@RequestBody ChannelArticleDTO dto){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return Result.success(articleService.getArticleByChannelD(dto.getPageNum(),dto.getPageSize(),dto.getChannelId(),
                dto.getKeyword(),LocalDateTime.parse(dto.getLastUpdateTime(),formatter), dto.getFilter(),dto.getSubscribe()));
    }

    @Operation(summary = "改变用户订阅数")
    @PutMapping("/setFollower")
    public Result setFollower(@RequestParam("follower") Integer follower,@RequestParam("userId")Long userId){
        articleService.setFollower(follower,userId);
        return Result.success();
    }

    @GetMapping("/test")
    public Result<LocalDateTime> timeTest(){
        return Result.success(LocalDateTime.now());
    }

}
